use rusqlite::{ Connection };
use tauri::{
    path::BaseDirectory, 
    Manager
};
use std::{ 
    sync::OnceLock,
    collections::HashMap
 };

static DB_PATH: OnceLock<String> = OnceLock::new();
static CORE_CONFIG: OnceLock<HashMap::<String, serde_json::Value>> = OnceLock::new();

pub fn get_connect() -> Connection {
    match DB_PATH.get() {
        Some(path) => Connection::open(path).unwrap(),
        None => panic!("DB_PATH is not exists."),
    }
}

pub fn close(conn: Connection) {
    conn.close().unwrap();
}

pub fn init_db_path(app: &mut tauri::App) {
    let dbpath_key = "dbPath".to_string();

    let config_path = app.path().resolve("./config.json", BaseDirectory::Resource).unwrap();
    let config_file = std::fs::File::open(&config_path).unwrap();
    let mut core_config: HashMap<String, serde_json::Value> = serde_json::from_reader(config_file).unwrap();

    let db_path = core_config.get(&dbpath_key).unwrap().as_str().unwrap();
    let default_db_path = app.path().resolve("./app.db", BaseDirectory::Resource).unwrap();
    let default_db_path = default_db_path.to_string_lossy().to_string();

    let c = if db_path.trim().is_empty() { default_db_path.clone() } else { db_path.to_string().clone() };

    core_config.insert(dbpath_key, serde_json::Value::String(c.clone()));
    DB_PATH.set(c).unwrap();
    CORE_CONFIG.set(core_config).unwrap();
}

pub fn get_db_path() -> String {
    DB_PATH.get().unwrap().clone()
}

pub fn get_config() -> HashMap<String, serde_json::Value> {
    CORE_CONFIG.get().unwrap().clone()
}